package com.huika.dealontop.control.shops.holder;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.v4.view.AutoScrollViewPager;
import android.support.v4.view.PagerData;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.huika.dealontop.R;
import com.huika.dealontop.control.base.extend.BaseViewHolder;
import com.huika.dealontop.control.common.ViewPictureActivity;
import com.huika.dealontop.control.nearby.activity.GMapActivity;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.shops.activity.CommonSubbranchActivity;
import com.huika.dealontop.control.shops.activity.SubmitOrderActivity;
import com.huika.dealontop.control.shops.activity.UseBonusActivity;
import com.huika.dealontop.control.shops.adapter.PackageAdapter;
import com.huika.dealontop.support.domain.ProductDetailsBean;
import com.huika.dealontop.utils.DateTimeTool;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.KeywordContainer;
import com.huika.dealontop.views.LinearLineWrapLayout;
import com.huika.dealontop.views.MMAlert;
import com.huika.dealontop.views.ToastMsg;
import com.huika.huikalib.utils.MoneyShowTool;
import com.huika.huikalib.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2015/11/20 20:12 <br/>
 * Description: 团购详情  头部部分内容 控制器
 */
public class ProductDetailHeaderHolder1 extends BaseViewHolder<ProductDetailsBean> implements View.OnClickListener {

    private AutoScrollViewPager autoScrollViewPager;
    private TextView mTvTitle;
    private TextView mTvTimeLeft;
    private TextView mTvBought;
    private TextView mTvPackage;
    private View mPackageUnderLine;
    private TextView mTvPrice;
    private TextView mTvMarketPrice;
    private TextView mTvDiscount;
    private TextView mTvMerchantName;
    private TextView mTvTel;
    private TextView mTvLocation;

    private Button mBtnBuy;
    //评分相关
    private RatingBar mRbTaste;
    private RatingBar mRbEnvironment;
    private RatingBar mRbService;
    private TextView mTvTaste;
    private TextView mTvEnvironment;
    private TextView mTvService;
    private TextView tv_total_score;
    private KeywordContainer mServiceKeywords;

    private TextView tv_score_count;

    private IOSAlertDialog callDialog;
    private int packageIndex;
    private TextView mTvMarkedWords;
    private TextView mTvSubbranch;

    public int getPackageIndex() {
        return packageIndex;
    }

    private OnPackageChangedListener onPackageChangedListener;

    public interface OnPackageChangedListener {
        void onPackageChanged(ProductDetailsBean.PackageSelectBean packageSelectBean, int packageIndex);
    }

    public ProductDetailHeaderHolder1(Context context, View rootView) {
        super(context, rootView);
    }

    @Override
    protected View initView() {
//        return View.inflate(UIUtils.getContext(), R.layout.holder_product_detail_header1, null);
        //不会进来
        return null;
    }

    @Override
    protected void assignView(View rootView) {
        if (rootView != null) {
            autoScrollViewPager = (AutoScrollViewPager) rootView.findViewById(R.id.avp_product_detail_banner);
            autoScrollViewPager.setScaleType(ImageView.ScaleType.CENTER_CROP);
            autoScrollViewPager.setIndicatorTwoOrMore(true);
            autoScrollViewPager.setOnPageItemClickListener(new OnBannerPageItemClickListener());
            mTvTitle = (TextView) rootView.findViewById(R.id.tv_product_detail_title);
            mTvTimeLeft = (TextView) rootView.findViewById(R.id.tv_product_detail_time_left);
            mTvBought = (TextView) rootView.findViewById(R.id.tv_product_detail_bought);
            mTvPackage = (TextView) rootView.findViewById(R.id.tv_product_detail_package);
            mPackageUnderLine = rootView.findViewById(R.id.package_under_line);
            mTvPrice = (TextView) rootView.findViewById(R.id.tv_product_detail_price);
            mTvDiscount = (TextView) rootView.findViewById(R.id.tv_product_detail_discount);
            mTvMarketPrice = (TextView) rootView.findViewById(R.id.tv_product_detail_cost_price);
            mTvMarketPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
            mTvMerchantName = (TextView) rootView.findViewById(R.id.tv_product_detail_merchant_name);
            mTvTel = (TextView) rootView.findViewById(R.id.tv_product_detail_tel);
            mTvLocation = (TextView) rootView.findViewById(R.id.tv_product_detail_location);
            mTvSubbranch = (TextView) rootView.findViewById(R.id.tv_product_detail_subbranch);
            mBtnBuy = (Button) rootView.findViewById(R.id.btn_product_detail_buy);
            mTvMarkedWords = (TextView) rootView.findViewById(R.id.tv_layout_marked_words);

            mServiceKeywords = (KeywordContainer) findViewById(R.id.kc_merchant_services_tags);
            mServiceKeywords.setKeywordViewFactory(new ServiceKeywordViewFactory());

            //评分相关
            mRbTaste = (RatingBar) rootView.findViewById(R.id.rb_taste);
            mRbEnvironment = (RatingBar) rootView.findViewById(R.id.rb_environment);
            mRbService = (RatingBar) rootView.findViewById(R.id.rb_service);
            mTvTaste = (TextView) rootView.findViewById(R.id.tv_taste);
            mTvEnvironment = (TextView) rootView.findViewById(R.id.tv_environment);
            mTvService = (TextView) rootView.findViewById(R.id.tv_service);
            tv_total_score = (TextView) rootView.findViewById(R.id.tv_total_score);
            tv_score_count = (TextView) rootView.findViewById(R.id.tv_comments_count);

            mTvPackage.setOnClickListener(this);
            mTvMerchantName.setOnClickListener(this);
            mTvTel.setOnClickListener(this);
            mTvLocation.setOnClickListener(this);
            mTvSubbranch.setOnClickListener(this);
            mBtnBuy.setOnClickListener(this);

        }
    }

    class ServiceKeywordViewFactory implements KeywordContainer.KeywordViewFactory {
        @Override
        public TextView makeKeywordView(int position, String text) {
            TextView tv = (TextView)View.inflate(mContext,R.layout.item_services_keyword, null);
            LinearLineWrapLayout.LayoutParams layoutParams = new LinearLineWrapLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, UIUtils.dip2px(26));
            layoutParams.setMargins(0, UIUtils.dip2px(10), UIUtils.dip2px(18), 0);
            tv.setLayoutParams(layoutParams);
            if(position == 0) {
                tv.setBackgroundResource(R.drawable.free_wifi_bg);
            }else if(position == 1) {
                tv.setBackgroundResource(R.drawable.free_drinks_bg);
            }else if(position == 2) {
                tv.setBackgroundResource(R.drawable.free_parking_bg);
            }else if(position == 3) {
                tv.setBackgroundResource(R.drawable.free_gift_bg);
            }else if(position == 4) {
                tv.setBackgroundResource(R.drawable.free_dessert_bg);
            }else if(position == 5) {
                tv.setBackgroundResource(R.drawable.free_door_service_bg);
            }
            return tv;
        }
    }

    private void showServicesKeywords(ProductDetailsBean.ProductBean.MerchantServicesBean merchantServices) {
        if (merchantServices == null || mServiceKeywords == null) {
//            merchantServices = new ProductDetailsBean.ProductBean.MerchantServicesBean();
            return;
        }

        if(!merchantServices.isIsFreeWifi() && !merchantServices.isIsFreeDrinks()
                && !merchantServices.isIsFreeParking() && !merchantServices.isIsGift()
                && !merchantServices.isIsDessert() && !merchantServices.isIsDoorService()){
            //一个服务都没有 隐藏
            findViewById(R.id.ll_merchant_services).setVisibility(View.GONE);
            return;
        }

        String[] keywords = new String[6];
        keywords[0] = merchantServices.isIsFreeWifi() ? UIUtils.getString(R.string.Merchant_free_wifi) : null;
        keywords[1] = merchantServices.isIsFreeDrinks() ? UIUtils.getString(R.string.Merchant_free_drinks) : null;
        keywords[2] = merchantServices.isIsFreeParking() ? UIUtils.getString(R.string.Merchant_free_parking) : null;
        keywords[3] = merchantServices.isIsGift() ? UIUtils.getString(R.string.Merchant_gift_tag) : null;
        keywords[4] = merchantServices.isIsDessert() ? UIUtils.getString(R.string.Merchant_dessert_tag) : null;
        keywords[5] = merchantServices.isIsDoorService() ? UIUtils.getString(R.string.Merchant_door_service_tag) : null;
        mServiceKeywords.setKeywords(keywords);
    }

    @Override
    protected void refreshView(ProductDetailsBean data) {
        refreshView(data, 0);
    }

    @Override
    protected void refreshView(ProductDetailsBean data, int packageIndex) {
        this.packageIndex = packageIndex;
        /* *
         * 轮播图
         */
        List<PagerData> datas = getBannerBean(data.getProductPicUrlList());
        if (datas != null) {
            autoScrollViewPager.setDatas(datas,
                    (LinearLayout) mRootView.findViewById(R.id.ll_product_detail_banner_indicator), true, true);
            autoScrollViewPager.start(5000); //5秒
        }

        /* *
         * 套餐
         */
        if (mData.getPackageSelect() != null && mData.getPackageSelect().size() > 1) {
            mTvPackage.setText(getPackageName());
        }else{
            //隐藏套餐选择
            mTvPackage.setVisibility(View.GONE);
            mPackageUnderLine.setVisibility(View.GONE);
        }

        /* *
         *  产品信息
         */
        ProductDetailsBean.ProductBean product = data.getProduct();
        if (product != null) {
            mTvTitle.setText(product.getProductName());
            new ProductCountDownTimer(((long) product.getSurplusTime())).start();
//            mTvTimeLeft.setText(DateTimeTool.getCountdownTimeMDHMS((long) product.getSurplusTime()));
            mTvBought.setText(UIUtils.getFormatString(R.string.some_people_buy, product.getPurchasedNum()));
            mTvPrice.setText(MoneyShowTool.twolastDF(product.getSalePrice(), false));
            mTvMarketPrice.setText(UIUtils.getString(R.string.list_price) + " ฿" + MoneyShowTool.nolastDF(product.getMarketPrice()));
            mTvDiscount.setText(MoneyShowTool.nolastDF(product.getDiscount(), false) + "% Off");
            mTvMerchantName.setText(product.getMerchantName());
            mTvTel.setText(getDisplayPhoneNumber());
            mTvLocation.setText(product.getMerchantAddress());

            //评分
            if(product.getTotalPriceScore() == 0){
                product.setTotalPriceScore(5);
            }
            if(product.getTotalEnvironmentScore() == 0){
                product.setTotalEnvironmentScore(5);
            }
            if(product.getTotalServiceScore() == 0){
                product.setTotalServiceScore(5);
            }
            mRbTaste.setRating((float) product.getTotalPriceScore());
            mRbEnvironment.setRating((float) product.getTotalEnvironmentScore());
            mRbService.setRating((float) product.getTotalServiceScore());
            mTvTaste.setText(MoneyShowTool.formatOne(product.getTotalPriceScore()));
            mTvEnvironment.setText(MoneyShowTool.formatOne(product.getTotalEnvironmentScore()));
            mTvService.setText(MoneyShowTool.formatOne(product.getTotalServiceScore()));

            if(product.getTotalScore() == 0){
                product.setTotalScore(5);
            }
            tv_total_score.setText(MoneyShowTool.formatOne(product.getTotalScore()));
            tv_score_count.setText(UIUtils.getFormatString(R.string.Merchant_pingjianum, product.getCommentCount()));

            initUseLayout(product);

            //提供的服务
            showServicesKeywords(product.getMerchantServices());

            //分店
            if(product.getMerchantCount() > 1){ //两家分店或以上才显示
                mTvSubbranch.setText(UIUtils.getFormatString(R.string.subbranch, product.getMerchantCount()));
            }else {
                //隐藏分店
                findViewById(R.id.ll_product_detail_subbranch_layout).setVisibility(View.GONE);
            }
        }
    }

    private void initUseLayout(ProductDetailsBean.ProductBean product) {
        boolean visible = product.isIsBespeak() || product.isIsUniversalTime() || product.isGeneralHolidays();
        findViewById(R.id.line_use_layout).setVisibility(visible ? View.VISIBLE : View.GONE);
        findViewById(R.id.ll_use_layout).setVisibility(visible ? View.VISIBLE : View.GONE);
        if(visible){
            findViewById(R.id.rl_not_book).setVisibility(product.isIsBespeak() ? View.VISIBLE : View.GONE);
            findViewById(R.id.rl_all_time_use).setVisibility(product.isIsUniversalTime() ? View.VISIBLE : View.GONE);
            findViewById(R.id.rl_general_holidays_use).setVisibility(product.isGeneralHolidays() ? View.VISIBLE : View.GONE);
        }
    }

    class OnBannerPageItemClickListener implements AutoScrollViewPager.OnPageItemClickListener<PagerData>{
        @Override
        public void onPageItemClickListener(PagerData pd) { }
        @Override
        public void onPageItemClickListener(List<PagerData> pagerData, int position) {
            if(pagerData == null) return;

            String[] arr = new String[pagerData.size()];
            for (int i = 0; i < pagerData.size(); i++) {
                arr[i] = pagerData.get(i).getImageUrl();
            }

            Intent intent = new Intent(mContext, ViewPictureActivity.class);
            intent.putExtra(ViewPictureActivity.PICTURE_ARRAY, arr);
            intent.putExtra(ViewPictureActivity.START_INDEX, position);
            mContext.startActivity(intent);
        }
    }

    private String retDate = "";
    class ProductCountDownTimer extends CountDownTimer{
        public ProductCountDownTimer(long millisInFuture) {
            super(millisInFuture, 1000); //一秒更新一次
        }
        @Override
        public void onTick(long millisInFuture) {
            try {
                retDate = DateTimeTool.getCountdownTimeMDHMS(millisInFuture / 1000);
            } catch (Exception e) {
                retDate = "";
                cancel();
            }finally {
                mTvTimeLeft.setText(retDate);
            }
        }
        @Override
        public void onFinish() {
            mTvTimeLeft.setText(UIUtils.getString(R.string.time_out));
        }
    }

    private String getDisplayPhoneNumber(){
        ProductDetailsBean.ProductBean product;
        if(mData == null || (product = mData.getProduct()) == null){
            return "";
        }
        return !StringUtils.isEmpty(product.getMerchantPhone()) ? StringUtils.formatTaiPhone(product.getMerchantPhone()) :
                StringUtils.isEmpty(product.getMerchantTel()) ? "" :
                        StringUtils.isEmpty(product.getExt()) ? StringUtils.formatTaiPhone(product.getMerchantTel()) :
                                StringUtils.formatTaiPhone(product.getMerchantTel()) + UIUtils.getString(R.string.common_ext) + product.getExt();
    }

    private String getCallNumber(){
        ProductDetailsBean.ProductBean product;
        if(mData == null || (product = mData.getProduct()) == null){
            return "";
        }
        return !StringUtils.isEmpty(product.getMerchantPhone()) ? product.getMerchantPhone() :
                !StringUtils.isEmpty(product.getMerchantTel()) ? product.getMerchantTel() : "";
    }

    private List getBannerBean(List<String> productPicUrlList) {
        if (productPicUrlList == null) {
            return null;
        }
        List<PagerData> datas = new ArrayList<>();
        PagerData data;
        for (String item : productPicUrlList) {
            data = new PagerData() {
                private String imgUrl;

                @Override
                public String getImageUrl() {
                    return imgUrl;
                }

                @Override
                public void setImageUrl(String imgUrl) {
                    this.imgUrl = imgUrl;
                }
            };
            data.setImageUrl(item);
            datas.add(data);
        }
        return datas;
    }

    /**
     * @return
     */
    protected String getPackageName() {
        ProductDetailsBean.PackageSelectBean aPackage = getPackage();
        if (aPackage != null) {
            return aPackage.getSkuName();
        }
        return null;
    }

    /**
     * @return
     */
    public ProductDetailsBean.PackageSelectBean getPackage() {
        if (mData.getPackageSelect() != null && mData.getPackageSelect().size() > packageIndex) {
            return mData.getPackageSelect().get(packageIndex);
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_product_detail_package) {
            //选择套餐
            showPackageDialog();
        } else if (id == R.id.tv_product_detail_merchant_name) {
            //商家主页
            ProductDetailsBean.ProductBean productBean = null;
            if(mData == null || (productBean = mData.getProduct()) == null){
                return;
            }
            Intent intent = new Intent(mContext,MerchantDetailActivity.class);
            intent.putExtra(MerchantDetailActivity.Product_ID, String.valueOf(productBean.getProductId()));
            intent.putExtra(MerchantDetailActivity.Merchant_ID, String.valueOf(productBean.getMerchantID()));
            mContext.startActivity(intent);

        } else if (id == R.id.tv_product_detail_tel) {
            final String number = StringUtils.formatTaiPhone(getCallNumber());
            if(!TextUtils.isEmpty(number)) {
                if(callDialog == null){
                    callDialog = DialogUtils.getInstance().createTitleDialog(mContext, number);
                    callDialog.setCancelText(UIUtils.getString(R.string.common_calcle));
                    callDialog.setConfirmText(UIUtils.getString(R.string.comm_call_phone));
                    callDialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            callDialog.dismiss();
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }
                    });
                }
                callDialog.show();
            }
            //打电话
        } else if (id == R.id.tv_product_detail_location) {
            ProductDetailsBean.ProductBean productBean;
            if (mData == null || (productBean = mData.getProduct()) == null) {
                return;
            }
            //打开地图
            Intent intent = new Intent(mContext, GMapActivity.class);
            intent.putExtra(GMapActivity.MERCHANTNAME,productBean.getMerchantName());
            intent.putExtra(GMapActivity.MERCHANTADDRESS,productBean.getMerchantAddress());
            intent.putExtra(GMapActivity.MERCHANTLAT,productBean.getLatitude());
            intent.putExtra(GMapActivity.MERCHANTLNG,productBean.getLongitude());
            Log.d("cy","详情经度："+productBean.getLatitude()+"详情维度："+productBean.getLongitude());
            mContext.startActivity(intent);
        }
        else if (id == R.id.btn_product_detail_buy) {
            ProductDetailsBean.ProductBean productBean;
            if (mData == null || (productBean = mData.getProduct()) == null) {
                return;
            }
            ProductDetailsBean.PackageSelectBean packageSelectBean = getPackage();
            if(packageSelectBean == null || packageSelectBean.getStock() < 1){
                ToastMsg.showToastMsg(mContext, UIUtils.getString(R.string.under_stock));
                return;
            }
            //购买
            Intent intent = new Intent(mContext, SubmitOrderActivity.class);
            intent.putExtra(GMapActivity.MERCHANTNAME,productBean.getProductName());
            intent.putExtra(GMapActivity.MERCHANTLNG,productBean.getLongitude());
//            intent.putExtra(SubmitOrderActivity.SALEPRICE,productBean.getSalePrice());
            intent.putExtra(UseBonusActivity.CITYID,productBean.getCityId());
            if(packageSelectBean != null){
                intent.putExtra(SubmitOrderActivity.PRODUCT_SKUID, packageSelectBean.getSKU_ProducId());
                intent.putExtra(SubmitOrderActivity.PRODUCT_SKUNAME,packageSelectBean.getSkuName());
                intent.putExtra(SubmitOrderActivity.PRODUCT_STOCK,packageSelectBean.getStock());
                intent.putExtra(SubmitOrderActivity.SKUPRICE, packageSelectBean.getSkuHKPrice());
            }
            mContext.startActivity(intent);
        }
        else if(id == R.id.tv_package_cancel){
            if(mPackageDialog != null && mPackageDialog.isShowing()){
                mPackageDialog.dismiss();
            }
        }
        else if(id == R.id.tv_product_detail_subbranch){
            ProductDetailsBean.ProductBean productBean;
            if (mData == null || (productBean = mData.getProduct()) == null) {
                return;
            }
            //打开分店列表
            Intent intent = new Intent(mContext, CommonSubbranchActivity.class);
            intent.putExtra(CommonSubbranchActivity.PRODUCTID, productBean.getProductId());
            intent.putExtra(CommonSubbranchActivity.LONGITUDEX, productBean.getLongitude() + "");
            intent.putExtra(CommonSubbranchActivity.DIMENSIONSY, productBean.getLatitude() + "");
            mContext.startActivity(intent);
        }
    }


    /****************************  套餐选择 ***********************************/
    private Dialog mPackageDialog;
    private View packageDialogCancel;
    private ListView mLvPackageList;
    private PackageAdapter packageAdapter;
    private void showPackageDialog() {
        if (mData == null || mData.getPackageSelect() == null ||  mData.getPackageSelect().size() < 1) {
            return;
        }
        if(mPackageDialog == null){
            mPackageDialog = MMAlert.createShowAlert(mContext,R.layout.choose_package_layout);
            mLvPackageList = (ListView) mPackageDialog.findViewById(R.id.lv_package_list);
            packageDialogCancel = mPackageDialog.findViewById(R.id.tv_package_cancel);
            mPackageDialog.findViewById(R.id.tv_package_cancel).setOnClickListener(this);
            packageAdapter = new PackageAdapter(mContext);
            packageAdapter.setGroup(mData.getPackageSelect());
            //初始化默认选中的
            getPackage().isSelect = true;
            mLvPackageList.setAdapter(packageAdapter);
            mLvPackageList.setOnItemClickListener(new PackageItemOnClickListener());
        }
        if(mPackageDialog.isShowing()){
            mPackageDialog.dismiss();
        }
        mPackageDialog.show();
    }

    /**
     *  套餐选择监听
     */
    class PackageItemOnClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (adapterView.getId() == R.id.lv_package_list) {
                List<ProductDetailsBean.PackageSelectBean> list = packageAdapter.getGroup();
                for (int a = 0; a < list.size(); a++) {
                    list.get(a).isSelect = false;
                }
                packageIndex = i;
                packageAdapter.getItem(i).isSelect = true;
                packageAdapter.notifyDataSetChanged();
                mPackageDialog.dismiss();

                refreshPackage();
            }
        }
    }

    public void setMarkedWords(String markedWords){
        if(mTvMarkedWords != null){
            mTvMarkedWords.setText(markedWords);
        }
    }

    private void refreshPackage() {
        mTvPackage.setText(getPackage().getSkuName());
        mTvPrice.setText(MoneyShowTool.twolastDF(getPackage().getSkuHKPrice(), false));
        mTvMarketPrice.setText(UIUtils.getString(R.string.list_price) + " ฿" + MoneyShowTool.nolastDF(getPackage().getSkuMarketPrice()));
        mTvDiscount.setText(MoneyShowTool.nolastDF(getPackage().getDiscount()) + "% Off");
        if(onPackageChangedListener != null){
            onPackageChangedListener.onPackageChanged(getPackage(), packageIndex);
        }
    }

    /****************************  套餐选择  end ***********************************/

}
